import json
import requests
import base64

def read_config(file_path):
    with open(file_path, 'r') as file:
        return json.load(file)

def add_or_update_datasource(grafana_url, username, password, data_source):
    auth = base64.b64encode(f"{username}:{password}".encode()).decode("utf-8")
    headers = {
        "Authorization": f"Basic {auth}",
        "Content-Type": "application/json"
    }
    
    # 获取现有数据源列表
    response = requests.get(f"{grafana_url}/api/datasources", headers=headers)
    if response.status_code != 200:
        raise Exception(f"Failed to fetch data sources: {response.text}")
    
    existing_data_sources = response.json()
    for existing_data_source in existing_data_sources:
        if existing_data_source["name"] == data_source["name"]:
            print(f"Data source '{data_source['name']}' already exists. Consider updating it instead of adding a new one.")
            return
    
    # 添加新数据源
    response = requests.post(f"{grafana_url}/api/datasources", headers=headers, json=data_source)
    if response.status_code == 200:
        print(f"Data source '{data_source['name']}' added successfully.")
    else:
        raise Exception(f"Error response from Grafana: {response.text}")

if __name__ == "__main__":
    config = read_config("config.json")
    
    # 遍历并添加每个数据源
    for data_source in config["dataSources"]:
        try:
            add_or_update_datasource(config["grafanaURL"], config["username"], config["password"], data_source)
        except Exception as e:
            print(f"Error adding data source: {str(e)}")
